package com.xbongbong.crm.perform.query.list.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmListQryService;
import com.xbongbong.crm.handle.analysis.MarketActivityListAnalysisDataHandler;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.FormDataFormExplainHelper;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.explain.HandleExplainHelp;
import com.xbongbong.parent.parse.data.FormDataListAnalysisDataHelp;
import com.xbongbong.parent.pojo.list.ConditionListPojo;
import com.xbongbong.parent.pojo.list.ConditionListResultPoJo;
import com.xbongbong.parent.pojo.list.DataAnalysisListPojo;
import com.xbongbong.parent.pojo.list.FieldListPojo;
import com.xbongbong.parent.pojo.list.PermissionListPojo;
import com.xbongbong.pro.applist.pojo.AppListPojo;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.HandleExplainPojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.service.toolbox.help.AnalysisSaasDataListHelp;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author sunshaoxiang
 * @ClassName MarketActivityListServiceImpl
 * @Description 市场活动详情页 业务层
 * @Date 2022/6/13 16:17
 * @Version 1.0
 **/
@Service("marketActivityListServiceImpl")
public class MarketActivityListServiceImpl extends AbstractCrmListQryService {

    public static final Logger LOGGER = LoggerFactory.getLogger(MarketActivityListServiceImpl.class);

    @Resource
    private HandleExplainHelp handleExplainHelp;
    @Resource
    private FormDataListAnalysisDataHelp formDataListAnalysisDataHelp;
    @Resource
    private MarketActivityListAnalysisDataHandler marketActivityListAnalysisDataHandler;
    @Resource
    private AnalysisSaasDataListHelp analysisSaasDataListHelp;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;
    @Resource
    private FormDataFormExplainHelper formDataFormExplainHelper;

    @Override
    public List<Integer> businessType() {
        return Collections.singletonList(XbbRefTypeEnum.MARKET_ACTIVITY.getCode());
    }

    @Override
    public List<ConditionsEntityExt> getPermission(PermissionListPojo permissionListPojo) throws XbbException {
        UserVO userVO = permissionListPojo.getUserVO();
        if (userVO.isMaxDataPermission()){
            return new ArrayList<>();
        }
        return getTeamUserPermission(userVO);

    }

    @Override
    public ConditionListResultPoJo getCondition(ConditionListPojo conditionListPojo) throws XbbException {
        try {
            //封装公共查询条件
            commonCondition(conditionListPojo);
            webCommonFilter(conditionListPojo);
            return new ConditionListResultPoJo(conditionListPojo.getConditionList(), conditionListPojo.getShouldConditionList());
        } catch (XbbException e) {
            LOGGER.error("com.xbongbong.crm.perform.query.list.impl.MarketActivityListServiceImpl.getCondition error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 封装公共查询条件
     * @param conditionListPojo
     */
    private void commonCondition(ConditionListPojo conditionListPojo) throws XbbException {
        setCommonCondition(conditionListPojo);
    }

    @Override
    public ConditionListResultPoJo mobileGetCondition(ConditionListPojo conditionListPojo) throws XbbException {
        //封装公共查询条件
        commonCondition(conditionListPojo);

        // app端独有范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionListPojo.getConditionList(), conditionListPojo.getUserVO(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), conditionListPojo.getSubBusinessType(), conditionListPojo.getPlatform());
        return new ConditionListResultPoJo(conditionListPojo.getConditionList(), conditionListPojo.getShouldConditionList());
    }

    @Override
    public HandleExplainPojo getExplain(FieldListPojo fieldListPojo) throws XbbException {
        List<String> fieldList = new ArrayList<>();
        List<FieldAttrEntity> explainList = commonGetExplain(fieldListPojo, fieldList);
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO(explainList, fieldListPojo.getForm(), fieldListPojo.getCorpid(), fieldListPojo.getUserVO().getUserId(), fieldListPojo.getUserVO(), true, fieldListPojo.getSubBusinessType());
        HandlerExplainVO handlerExplainVO = handleExplainHelp.handleExplain(handlerExplainDTO);

        HandleExplainPojo handleExplainPojo = new HandleExplainPojo();
        explainList = handlerExplainVO.getHeadList();
        handleExplainPojo.setExplainList(explainList);
        handleExplainPojo.setFieldList(fieldList);
//        handleExplainPojo.setUpdateTime(paasFormExplainEntity.getUpdateTime());

        return handleExplainPojo;
    }

    @Override
    public List<PaasFormDataEntityExt> webDataAnalysis(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {
        List<FieldAttrEntity> explainList = dataAnalysisListPojo.getExplainList();
        List<PaasFormDataEntityExt> formDataList = dataAnalysisListPojo.getFormDataList();
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(JSONArray.toJSONString(explainList), null);
        String corpid = dataAnalysisListPojo.getCorpid();
        String userId = dataAnalysisListPojo.getUserId();
        Integer businessType = dataAnalysisListPojo.getBusinessType();
        FormDataListDTO formDataListDTO = new FormDataListDTO(dataAnalysisListPojo.getCorpid(), dataAnalysisListPojo.getFormId(), dataAnalysisListPojo.getSaasMark(), dataAnalysisListPojo.getBusinessType(), dataAnalysisListPojo.getSubBusinessType(), dataAnalysisListPojo.getDistributorMark(), dataAnalysisListPojo.getUserVO(), dataAnalysisListPojo.getAnalysisAmountOfThousandBitsWithOriginalValue());
        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        formDataListVO.setPaasFormDataESList(formDataList);
        formDataListVO.setHeadList(dataAnalysisListPojo.getExplainList());
        if (formDataList == null || formDataList.isEmpty()) {
            return formDataList;
        }

        marketActivityListAnalysisDataHandler.analysisDataList(formDataListDTO, formDataListVO);
        marketActivityListAnalysisDataHandler.analysisAmountOfThousandBits(formDataListVO, dataAnalysisListPojo.getAnalysisAmountOfThousandBitsWithOriginalValue());

        return formDataListVO.getPaasFormDataESList();
    }

    @Override
    public List<PaasFormDataEntityExt> dingtalkDataAnalysis(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {
        try {
            List<PaasFormDataEntityExt> formDataList = dataAnalysisListPojo.getFormDataList();

            FormDataListDTO formDataListDTO = new FormDataListDTO(dataAnalysisListPojo.getCorpid(), dataAnalysisListPojo.getFormId(), dataAnalysisListPojo.getSaasMark(), dataAnalysisListPojo.getBusinessType(), dataAnalysisListPojo.getSubBusinessType(), dataAnalysisListPojo.getDistributorMark(), dataAnalysisListPojo.getUserVO(), dataAnalysisListPojo.getAnalysisAmountOfThousandBitsWithOriginalValue());

            PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
            formDataListVO.setHeadList(dataAnalysisListPojo.getExplainList());
            formDataListVO.setPaasFormDataESList(formDataList);
            formDataListVO.setForm(dataAnalysisListPojo.getForm());
            formDataListVO.setForm(dataAnalysisListPojo.getForm());

            marketActivityListAnalysisDataHandler.analysisDataList(formDataListDTO, formDataListVO);
            marketActivityListAnalysisDataHandler.analysisAmountOfThousandBits(formDataListVO, false);

            // 摘要和标题的封装
            formDataListVO = ExplainUtil.getValueByData(formDataListVO, formDataListDTO.getFormMap(), dataAnalysisListPojo.getFormIdAndHeadListMap());
            return formDataListVO.getPaasFormDataESList();
        } catch (Exception e) {
            LOGGER.error("com.xbongbong.crm.list.ContactListServiceImpl.dingtalkDataAnalysis error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public List<AppListPojo> dingtalkOperate(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {
        List<AppListPojo> appListPojos = new ArrayList<>();
        String corpid = dataAnalysisListPojo.getCorpid();
        List<PaasFormDataEntityExt> esEntities = dataAnalysisListPojo.getFormDataList();

        List<Long> marketActivityIn = esEntities.stream().map(entity -> entity.getDataId()).collect(Collectors.toList());
        //协同团队
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        formDataFormExplainHelper.getUserIdMap(marketActivityIn,corpid,dataAnalysisListPojo.getBusinessType(),false ,mainUserMap,coUserMap);
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(dataAnalysisListPojo, handlerExplainDTO);
        //详情 摘要 标签 处理
        JSONObject defaultJson = new JSONObject();
        for(PaasFormDataEntityExt marketActivityEntity : esEntities){
            long id = marketActivityEntity.getDataId();
            long appId = marketActivityEntity.getAppId();
            long menuId = marketActivityEntity.getMenuId();
            long formId = marketActivityEntity.getFormId();
            JSONObject data = marketActivityEntity.getData();


            List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
            //app系统关联数据展示时，前端需要 others 信息用来判断
            data.put("others",defaultJson);
            data.put("superScript" ,defaultJson);
            appListPojos.add(new AppListPojo(id, titleList, summaryList, defaultJson, lablesList, defaultJson, appId, menuId, formId));
        }
        return appListPojos;
    }

    @Override
    public void webOperate(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {

    }
}
